package com.shm.leetcode.concurrent;

class H2O_1 {

    public H2O_1() {
        
    }
    Object object = new Object();

    private volatile int h=2;
    private volatile boolean hydrogen=true;
    private volatile boolean oxygen=true;
    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        synchronized (object) {
            while (!hydrogen) {
                object.wait();
            }
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();
            h--;
            if (h == 0) {
                hydrogen = false;
                oxygen = true;
                h=2;
            }
            object.notifyAll();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        synchronized (object) {
            while (!oxygen) {
                object.wait();
            }
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
            releaseOxygen.run();
            oxygen=false;
            hydrogen=true;
            object.notifyAll();
        }
    }
}